package com.lambkit.db.enjoy;

import com.jfinal.template.Engine;
import com.jfinal.template.Template;
import com.lambkit.db.Sql;

import java.util.HashMap;
import java.util.Map;

public class EnjoySQL {
    private String configName;
    private boolean devMode;
    private Engine engine;

    public EnjoySQL(String configName, boolean devMode) {
        this.configName = configName;
        this.devMode = devMode;
        this.engine = new Engine(configName);
        this.engine.setDevMode(devMode);
        this.engine.setToClassPathSourceFactory();
        this.engine.addDirective("para", ParaDirective.class, true);
        this.engine.addDirective("p", ParaDirective.class, true);
    }

    public EnjoySQL(String configName) {
        this(configName, false);
    }

    public Engine getEngine() {
        return this.engine;
    }

    public void setDevMode(boolean devMode) {
        this.devMode = devMode;
        this.engine.setDevMode(devMode);
    }

    public Sql getSqlPara(String content, Map data) {
        Template template = this.engine.getTemplateByString(content);
        Sql sqlPara = new Sql();
        data.put("_SQL_PARA_", sqlPara);
        sqlPara.setSql(template.renderToString(data));
        data.remove("_SQL_PARA_");
        return sqlPara;
    }

    public Sql getSqlPara(String content, Object... paras) {
        Template template = this.engine.getTemplateByString(content);
        Sql sqlPara = new Sql();
        Map data = new HashMap();
        data.put("_SQL_PARA_", sqlPara);
        data.put("_PARA_ARRAY_", paras);
        sqlPara.setSql(template.renderToString(data));
        return sqlPara;
    }
}
